package com.terrier.ui.effects
{
	import com.terrier.ui.events.WxEffectEvent;
	
	import flash.display.DisplayObject;
	
	public class WxConcurrentEffect extends WxAbstractEffect
	{
		private var _arrEffects:Array;
		private var _anchorEffect:WxAbstractEffect;
		
		public function WxConcurrentEffect(arrEffects:Array, target:DisplayObject = null,
										   startEventParams:Object = null,
										   updateEventParams:Object = null,
										   stopEventParams:Object = null)
		{	
			this._arrEffects = arrEffects;
			this.findLongestRuntimeEffect();
			super(target, 0.0, startEventParams, updateEventParams, stopEventParams);
			this.target = target;
		}
		
		public function findLongestRuntimeEffect():void
		{
			if(this._arrEffects == null || this._arrEffects.length == 0)
			{
				return;
			}
			
			this._anchorEffect = this._arrEffects[0];
			for(var i:int = 1; i < this._arrEffects.length; ++i)
			{
				if(this._arrEffects[i].runTime > this._anchorEffect.runTime)	
				{
					this._anchorEffect = this._arrEffects[i];
				}
			}
		}
		
		protected override function initialize():void
		{
			if(this._arrEffects == null || this._anchorEffect == null)
			{
				throw new Error("There are no valid effects registered under concurrent effects");
			}
		}
		
		public override function start():void
		{
			super.start();
			
			this._anchorEffect.addEventListener(WxEffectEvent.EFFECT_STOP, allEffectsEndedHandler);
			for each(var effect:WxAbstractEffect in this._arrEffects)
			{
				effect.start();	
			}
		}
		
		private function allEffectsEndedHandler(event:WxEffectEvent):void
		{
			this._anchorEffect.removeEventListener(WxEffectEvent.EFFECT_STOP, allEffectsEndedHandler);
			this.stop();
		}
		
		public override function stop():void
		{
			for each(var effect:IWxAbstractEffect in this._arrEffects)
			{
				if(effect.running)
				{
					effect.stop();
				}
			}
			super.stop();
		}
		
		public function get arrEffects():Array
		{
			return this._arrEffects;
		}
		
		public function get anchorEffect():WxAbstractEffect
		{
			return this._anchorEffect;
		}
		
		public override function set target(value:DisplayObject):void
		{
			super.target = value;
			for each(var effect:WxAbstractEffect in this._arrEffects)
			{
				effect.target = value;
			}
		}
		
		public override function clone():IWxAbstractEffect
		{
			var newEffect:WxConcurrentEffect = new WxConcurrentEffect(
				this.arrEffects, this.target,
				this.startEventParams, this.updateEventParams, this.stopEventParams);			
			newEffect._anchorEffect = this._anchorEffect;
			return newEffect;
		}
	}
}